<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Install extends Start_Controller {
	
	public function __construct(){
		parent::__construct();
		$this->data['theme_url'] = base_url('template/default/install');
 	}
	
	public function index()
	{
		$this->data['pagename'] = '安装程序';
		$this->_template('install/index',$this->data);
	}
	
	
	public function step1() {
	
		//环境检测配置
		$env['phpversion'] = array('curr_version'=> phpversion(),'lowest_version'=>'5.2.0','check'=>true);
	
		//PHP库检测配置
		$func['mysql'] = array('func'=>'mysql_connect','check'=>true);
		$func['GD']	= array('func'=>'gd_info','check'=>true);
		////d$func['iconv'] = array('func'=>'iconv','check'=>true);
		//$func['JSON'] = array('func'=>'json_encode','check'=>true);
		//$func['CURL'] = array('func'=>'curl_init','check'=>true);
	
		//权限检测配置
		$files['data'] = 								array('lowest_attrib'=>'777','curr_attrib'=>'','check'=>true);
		$files['data/attached'] = 						array('lowest_attrib'=>'777','curr_attrib'=>'','check'=>true);
		$files['data/cache'] = 					array('lowest_attrib'=>'777','curr_attrib'=>'','check'=>true);
		$files['data/cache/compile'] = 					array('lowest_attrib'=>'777','curr_attrib'=>'','check'=>true);
		$files['data/cache/template'] = 				array('lowest_attrib'=>'777','curr_attrib'=>'','check'=>true);
		$files['config'] = 					array('lowest_attrib'=>'660','curr_attrib'=>'','check'=>true);
		//$files['application/config/custom.php'] = 		array('lowest_attrib'=>'','curr_attrib'=>'','check'=>true);
		//$files['application/config/database.php'] = 	array('lowest_attrib'=>'','curr_attrib'=>'','check'=>true);
		//$files['application/config/routes.php'] = 		array('lowest_attrib'=>'','curr_attrib'=>'','check'=>true);
		//$files['application/config/seo_setting.php'] = 	array('lowest_attrib'=>'','curr_attrib'=>'','check'=>true);
		//$files['application/config/database.php'] = 	array('lowest_attrib'=>'','curr_attrib'=>'','check'=>true);
		//$files['application/config/user_badword.php'] = array('lowest_attrib'=>'','curr_attrib'=>'','check'=>true);
	
		//分别进行检测，结果计入$check_result
		$check_result = array();
		$check_result['env'] = $env;
		$check_result['func'] = $func;
		$check_result['files'] = $files;
		$check_result['total_check'] = true;
	
		//环境检测
		foreach($env as $key=>$value) {
			if (strnatcmp($env[$key]['curr_version'],$env[$key]['lowest_version']) < 0) {
				$check_result['env'][$key]['check'] = false;
				$check_result['total_check'] = false;
			}
		}
	
		//PHP库检测
		foreach($func as $key=>$value) {
			if(!function_exists($value['func'])){
				$check_result['func'][$key]['check'] = false;
				$check_result['total_check'] = false;
			}
	
		}
	
		//文件权限检测
		$this->load->helper('file');
		foreach($files as $key=>$value) {
			$attrib = octal_permissions(@fileperms(FCPATH.$key));
			$check_result['files'][$key]['curr_attrib'] = $attrib;
				
			if(is_dir(FCPATH.$key)){
				if($attrib != '777'){
					$check_result['files'][$key]['check'] = false;
					$check_result['total_check'] = false;
				}
			}else{
				if(!is_writable(FCPATH.$key) ){
					$check_result['files'][$key]['check'] = false;
					$check_result['total_check'] = false;
				}
			}
		}
	
		$this->data['check_result'] = $check_result;
		
		$this->_template('install/step1', $this->data, false);
	}
	
	
	
	public function step2() {
		
		if($this->input->post()){
	
			$db='';
			//数据库配置信息
			$db['hostname'] = $this->input->post('db_hostname',true);
			$db['username'] = $this->input->post('db_username',true);
			$db['password'] = $this->input->post('db_password',true);
			$db['database'] = $this->input->post('db_database',true);
			$db['dbprefix'] = $this->input->post('db_dbprefix',true);
			if($db['dbprefix']) {
				$db['dbprefix'] = (substr($db['dbprefix'],-1) == '_') ? $db['dbprefix'] : $db['dbprefix'].'_';
			}
			$drop_tables = $this->input->post('drop_table',true);
				
			//管理员账号
			$adm_user['adm_user'] = $this->input->post('adm_user',true);
			$adm_user['adm_passwd'] = $this->input->post('adm_passwd',true);
 	
			//载入文件读写函数
			$this->load->helper('file');
				
			//修改数据库配置文件
			$database_example_file = FCPATH . 'config/config.example.php';
			$database_out_file = FCPATH . 'config/config.php';
			$database_conf = read_file($database_example_file);
			
			$database_conf = str_replace(
					array('{hostname}','{username}','{password}','{database}','{dbprefix}'),
					array($db['hostname'],$db['username'],$db['password'],$db['database'],$db['dbprefix']),
					$database_conf);
			$break = false;
			//开始写入文件
			if(!$break) {
				if (! write_file($database_out_file, $database_conf) ){
					$this->data['message'] = '数据库配置文件写入失败，请检查文件权限:';
					$break = true;
				}
			}
			if(!$break) {
				//执行数据库导入
				$result = $this->import_sql($db,$drop_tables,$adm_user);
				if($result['status'] == 200){
					redirect('install/step3');
				}else{
					$this->data['message'] = $result['message'];
				}
			}
				
		}
		if(!empty($adm_user))$this->data['adm_user'] = $adm_user;
		if(!empty($db))$this->data['db'] = $db;
	
		$this->_template('install/step2', $this->data);
	}
	
	public function step3() {
	
		//修改路由配置文件
		$routes_file = FCPATH . 'source/app/config/routes.php';
		$routes_conf = read_file($routes_file);
		$routes_conf = str_replace('install/index','Start',$routes_conf);
	
		if ( ! write_file($routes_file, $routes_conf) ){
			$this->data['message'] = '路由配置文件写入失败，请检查文件权限';
		}
	
 		$this->_template('install/step3', $this->data, false);
	}
	
	
 
	
	
	public function import_sql($db,$drop_table = false,$adm_user){
	
		if(!$db['hostname']  || !$db['username'] || !$db['database'] ){
			return array('status'=>500,'message'=>'数据库配置信息不完整，请确保填写完整');
		}
	
		if(!$adm_user['adm_user']  || !$adm_user['adm_passwd']   ){
			return array('status'=>500,'message'=>'管理员账号信息不完整，请确保填写完整');
		}
	
		//初使化数据库
		$link = @mysql_connect($db['hostname'], $db['username'], $db['password']);
		if (!$link) {
			return array('status'=>500,'message'=>'数据库链接失败，请检查用户名密码配置是否正确');
		}
		if(!mysql_select_db($db['database'], $link)){
			return array('status'=>500,'message'=>'数据库不存在，请先建立数据库后再进行安装');
		}
		mysql_query("SET NAMES utf8");
	
	
		//处理上次安装的数据
		$old_table = $db['dbprefix'];
		$sql = "SHOW TABLE STATUS LIKE  '%{$old_table}%'";
		$result = mysql_query($sql);
		if( mysql_num_rows($result) > 0 ){
			if($drop_table){
				while($row = mysql_fetch_array($result))
				{
					mysql_query("drop table {$row['Name']}");
				}
			}else{
				return array('status'=> 500 ,'message'=> '数据表已存在，只有清除原数据表才能继续安装。' );
			}
		}
	
	
		//导入SQL文件
		
		$sql_file = read_file(FCPATH.'data/sql/taygod.sql');
	 
		$sql_file = $this->_DoRunQuery($sql_file,'utf8',$db['dbprefix'],'5.1');
		
		if(!$sql_file){
			return array('status'=> 500,'message'=> '安装文件不完整，请重新下载安装包。' );
		}
	
		 
		
		//创建管理员账号
		$adm_email = $adm_user['adm_user'];
		$adm_passwd = sha1($adm_user['adm_passwd']);
 		$dbprefix = $db['dbprefix'];
	
		$sql = "UPDATE  `{$dbprefix}member` SET  `username` =  '{$adm_email}', `password` =  '{$adm_passwd}'   WHERE  `id` =1;";
	
		$result = mysql_query($sql);
	
		if (!$result) {
			return array('status'=>500,'message'=> '管理员账号建立失败，请重新安装。' );
		}
	
	
		return array('status'=>200,'message'=> '数据库导入成功' );
	
	
	
	
	}
	
	
	//运行SQL
	function _DoRunQuery($sql,$mydbchar,$mydbtbpre,$mydbver){
		$sql=str_replace("\r","\n",str_replace('{dbprefix}',$mydbtbpre,$sql));
		$ret=array();
		$num=0;
		foreach(explode(";\n",trim($sql)) as $query)
		{
			$queries=explode("\n",trim($query));
			foreach($queries as $query)
			{
				@$ret[$num].=$query[0]=='#'||$query[0].$query[1]=='--'?'':$query;
				
			}
			$num++;
		}
		unset($sql);
		foreach($ret as $query)
		{
			$query=trim($query);
			if($query)
			{
				if(substr($query,0,12)=='CREATE TABLE')
				{
					$name=preg_replace("/CREATE TABLE `([a-z0-9_]+)` .*/is","\\1",$query);
					//echo"建立数据表: <b>".$name."</b> 完毕......<br>";
					mysql_query($this->_DoCreateTable($query,$mydbver,$mydbchar)) or die(mysql_error()."<br>".$query);
				}
				else
				{
					if (!mysql_query($query)) {
						$message  = '数据库执行错误: ' . mysql_error() . "\n<br />".$query;
						$message .= 'SQL语句: ' . $sql;
						return array('status'=> 500,'message'=> $message );
					}
				}
			}
		}
		return  TRUE;
	}
	
	//建表
	function _DoCreateTable($sql,$mysqlver,$dbcharset){
		$type=strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU","\\2",$sql));
		$type=in_array($type,array('MYISAM','HEAP'))?$type:'MYISAM';
		return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU","\\1",$sql).
			($mysqlver>='4.1'?" ENGINE=$type DEFAULT CHARSET=$dbcharset":" TYPE=$type");
	}
	
	 
 
}

 
